package org.yty.travelagencyredis.Dao.impl;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.yty.travelagencyredis.Dao.SignUpDao;
import org.yty.travelagencyredis.model.Entity.SignUp;

import java.util.List;

@Repository
@RequiredArgsConstructor
public class SignUpDaoImpl implements SignUpDao {
    private final StringRedisTemplate redisTemplate;

    @Override
    public List<SignUp> getListByTourGroupId(Long tourGroupId) {
        return this.redisTemplate.opsForHash().values(SignUp.key)
                .stream().map(item -> JSON.parseObject((String) item, SignUp.class))
                .filter(item -> item.getTourGroupId().equals(tourGroupId)).toList();
    }

    @Override
    public List<SignUp> selectByTravellerId(Long travellerId) {
        return this.redisTemplate.opsForHash().values(SignUp.key).stream().
                map(item -> JSON.parseObject((String) item, SignUp.class))
                .filter(item -> item.getTravellerId().equals(travellerId))
                .toList();
    }

    @Override
    public void deleteByTourGroupIdAndTravellerId(Long tourGroupId, Long travellerId) {
        this.redisTemplate.opsForHash().values(SignUp.key).stream()
                .map(item -> JSON.parseObject((String) item, SignUp.class))
                .filter(item -> item.getTourGroupId().equals(tourGroupId) && item.getTravellerId().equals(travellerId))
                .forEach(item -> this.redisTemplate.opsForHash().delete(SignUp.key, item.getId()));
    }

    @Override
    public boolean insert(SignUp signUp) {
        this.redisTemplate.opsForHash().put(SignUp.key, signUp.getId(), JSON.toJSONString(signUp));
        return true;
    }

    @Override
    public boolean save(SignUp signUp) {
        this.redisTemplate.opsForHash().put(SignUp.key, signUp.getId(), JSON.toJSONString(signUp));
        return true;
    }

    @Override
    public void deleteByTravellerId(Long travellerId) {
        this.redisTemplate.opsForHash().values(SignUp.key)
                .stream().map(item -> JSON.parseObject((String) item, SignUp.class))
                .filter(item -> item.getTravellerId().equals(travellerId))
                .forEach(item -> this.redisTemplate.opsForHash().delete(SignUp.key, item.getId()));
    }

    @Override
    public void deleteByTourGroupId(Long tourGroupId) {
        this.redisTemplate.opsForHash().values(SignUp.key)
                .stream().map(item -> JSON.parseObject((String) item, SignUp.class))
                .filter(item -> item.getTourGroupId().equals(tourGroupId))
                .forEach(item -> this.redisTemplate.opsForHash().delete(SignUp.key, item.getId()));
    }
}
